package com.example.zhidao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.zhidao.model.po.Views;
import com.example.zhidao.model.responseData.ResponseData;
import com.example.zhidao.service.ViewsService;
import com.example.zhidao.utils.Ujwt;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/views")
public class ViewsController {//1

    @Autowired
    Ujwt ujwt;

    @Autowired
    ViewsService viewsService;

//    增加观看次数
    @PostMapping("/addViews")
    public ResponseData addViews(@RequestHeader("token")String token, String bid){
        Claims claims=(Claims)ujwt.tokenToOut(token);//强制转换属性
        String uid=claims.getId();//解出token，获取用户的id

//        先通过uid查询是否存在观看关系
        QueryWrapper<Views> qw=new QueryWrapper<>();
        qw.eq("uid",uid);
        qw.eq("bid",bid);
        Views v=viewsService.getOne(qw);
        if(v!=null) {
            return new ResponseData(null, false, "已经观看过了", 202);
        }else{
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");//自动生成uuid

            Views views=new Views();
            views.setId(uuid);
            views.setBid(bid);
            views.setUid(uid);

            boolean i=viewsService.addview(views);

            if(i){
                return new ResponseData(i,true,"成功",200);
            }else{
                return new ResponseData(i,false,"失败",201);
            }
        }


    }
}
